import { Button, DatePicker, Empty, Input, Message, Progress, Table } from '@arco-design/web-react';
import { AxiosResponse } from 'axios';
import dayjs from 'dayjs';
import { useEffect, useRef, useState } from 'react';
import main from '../main';
import { apiGetTaskMqExportList } from '../api';
import { clearEmptyKey, delay } from '../utils/utils';
import DetailModal from './detailModal';
import LoadingMask from './loadingMask';

interface TaskMQExport {
  appName?: string;
  className?: string;
  createTime?: string;
  dataJson: { exportName?: string; params: any };
  deptId?: number;
  deptName?: string;
  expireTime?: string;
  exportUrl?: string;
  groupId?: string;
  id?: string;
  name?: string;
  percentage?: number;
  remark?: string;
  status?: string;
  statusRemark?: string;
  tag?: string;
  topic?: string;
  updateTime?: string;
  userId?: number;
  userName?: string;
  version?: number;
}

interface Props {
  title: string;
  taskKey?: string;
  taskName?: string;
  params?: any;
  onlyDownload?: boolean;
  onCancel: () => void;
  exportFn?: (params: any) => Promise<AxiosResponse<any, any>>;
}
export default function ExportFileDialog({
  title,
  taskKey,
  taskName,
  params,
  onCancel,
  exportFn,
  onlyDownload,
}: Props) {
  const [list, setList] = useState<TaskMQExport[]>([]);
  const [fetching, setFetching] = useState(false);
  const [loaded, setLoaded] = useState(false);
  const [error, setError] = useState('');
  const [total, setTotal] = useState(1);
  const [pageNum, setPageNum] = useState(1);
  const [pageSize, setPageSize] = useState(main.defaultPageSize);

  const unmontRef = useRef(false);
  const pageRef = useRef({ pageNum, pageSize, init: false });

  // ----------------------------检索条件--------------
  const [name, setName] = useState(taskKey ?? taskName);
  const [beginTime, setBeginTime] = useState('');
  const [endTime, setEndTime] = useState('');

  useEffect(() => {
    if (!onlyDownload) {
      loadData();
    } else {
      loadProgress();
    }
    return () => {
      unmontRef.current = true;
    };
  }, []); //eslint-disable-line

  useEffect(() => {
    if (!pageRef.current.init) {
      pageRef.current.init = true;
    } else {
      loadProgress();
    }
  }, [pageNum, pageSize]); // eslint-disable-line

  async function loadData() {
    LoadingMask.show('正在加载...');
    setFetching(true);
    try {
      let res = await exportFn!(
        clearEmptyKey(
          Object.assign(
            {
              exportName: name,
              pageNum,
              pageSize,
            },
            params
          )
        )
      );
      let data = res.data;
      if (data.code === 200) {
        loadProgress();
      } else {
        setError(data.msg ?? '加载失败');
        setList([]);
      }
    } catch (e: any) {
      setError(e.message ?? '加载失败');
    } finally {
      LoadingMask.hide();
    }
  }

  async function loadProgress() {
    if (pageNum !== pageRef.current.pageNum || pageSize !== pageRef.current.pageSize) {
      return;
    }
    setFetching(true);
    try {
      let res = await apiGetTaskMqExportList(
        pageNum,
        pageSize,
        Object.assign({
          name,
          isAsc: 'desc',
          orderByColumn: 'id',
          params: { beginCreateTime: beginTime, endCreateTime: endTime },
        })
      );
      let data = res.data;
      if (!loaded) {
        setLoaded(true);
      }
      if (data.code === 200) {
        if (fetching) {
          setFetching(false);
        }
        if (!loaded) {
          setLoaded(true);
        }
        setTotal(data.total);
        setList(data.rows ?? []);
        let some = data.rows.some(
          (item: TaskMQExport) => item.status !== 'success' && item.status !== 'failure' && item.status !== 'error'
        );
        if (some) {
          await delay(1000);
          if (!unmontRef.current) {
            loadProgress();
          }
        }
      } else {
        setError(data.msg ?? '加载失败');
        Message.warning(data.msg ?? '加载失败');
        setList([]);
      }
    } catch (e: any) {
      Message.error(e.messag ?? '加载失败');
      setError(e.messag ?? '加载失败');
    }
  }

  function handleDownload(url?: string) {
    if (!url) return;
    window.open(url, '_brank');
  }

  /**
   * 分页器 切换分页和条数
   * @param page 当前页数
   * @param size 每页条数
   */
  function handlePageAndSizeChange(page: number, size: number) {
    if (page === pageNum && size === pageSize) return;

    Message.info('正在加载...');
    setPageSize(size);
    setPageNum(page);
    pageRef.current.pageNum = page;
    pageRef.current.pageSize = size;
  }

  let dataSource = (list || []).map((item) => Object.assign({}, item, { key: item.id }));

  // 定义类型表格内的列
  const dataColumns = [
    {
      title: '任务名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '进度',
      dataIndex: 'percentage',
      key: 'percentage',
      render: (v: number) => (
        <div className="w-200">
          <Progress percent={v} />
        </div>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (v: string) =>
        v === 'waiting' ? '排队中' : v === 'processing' ? '处理中' : v === 'success' ? '成功' : '异常',
    },
    {
      title: '状态提示',
      dataIndex: 'statusRemark',
      key: 'statusRemark',
      render: (v: string) => <div className="maxw-200">{v}</div>,
    },
    {
      title: '操作人',
      dataIndex: 'deptUserName',
      key: 'deptUserName',
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
    },
    {
      title: '下载地址',
      dataIndex: 'exportUrl',
      key: 'exportUrl',
      render: (v?: string) =>
        v ? (
          <div
            className="text-primary-color cursor-pointer"
            onClick={() => {
              Message.info('正在加载...');
              handleDownload(v);
            }}
          >
            下载
          </div>
        ) : undefined,
    },
  ];

  return (
    <DetailModal
      show
      title={title}
      cancelBtnShow={false}
      onConfirm={onCancel}
      onCancel={onCancel}
      className="w-1000 minh-500"
      contentClassName="minh-500 ac-start"
    >
      <Input
        allowClear
        className="mr-20 mb-20 search-input"
        placeholder="任务名"
        value={name}
        onChange={(v) => setName(v)}
      />
      <DatePicker.RangePicker
        allowClear
        showTime
        format="YYYY-MM-DD HH:mm:ss"
        className="mr-20 mb-20 search-range-picker"
        placeholder={['开始时间', '结束时间']}
        value={!beginTime || !endTime ? undefined : [dayjs(beginTime), dayjs(endTime)]}
        onChange={(dates) => {
          setBeginTime(dates?.[0] || '');
          setEndTime(dates?.[1] || '');
        }}
        onSelect={(dates) => {
          setBeginTime(dayjs(dates?.[0]).startOf('day').format('YYYY-MM-DD HH:mm:ss'));
          setEndTime(dayjs(dates?.[1]).endOf('day').format('YYYY-MM-DD HH:mm:ss'));
        }}
      />
      <Button type="primary" onClick={() => loadProgress()}>
        搜索
      </Button>
      <Table
        className="bw-100"
        data={dataSource}
        columns={dataColumns}
        loading={!list || (fetching && !loaded)}
        noDataElement={<Empty description={error ?? '暂无数据'} />}
        pagination={{
          className: 'pagination-block',
          total: total || 1,
          current: pageNum,
          pageSize: pageSize,
          showJumper: true,
          sizeCanChange: true,
          sizeOptions: main.defaultPageSizeOptions,
          showTotal: (total) => `共${total}条`,
          size: 'small',
          onChange: handlePageAndSizeChange,
        }}
      />
    </DetailModal>
  );
}
